﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BugzX.Models;
using BugzX.Repositories;
using System.Web.Security;

namespace BugzX.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Login(LoginRequest req)
        {
            bool res = UserRepository.ValidateUser(req.UserName, req.Password);

            if (res)
            {
                // from http://www.codethinked.com/setting-up-authentication-in-aspnet-mvc
                var authTicket = new FormsAuthenticationTicket(1, req.UserName, DateTime.Now,
                                                       DateTime.Now.AddMinutes(30), true, String.Empty);

                string cookieContents = FormsAuthentication.Encrypt(authTicket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                {
                    Expires = authTicket.Expiration,
                    Path = FormsAuthentication.FormsCookiePath
                };
                if (this.HttpContext != null)
                {
                    this.HttpContext.Response.Cookies.Add(cookie);
                }
            }

            return RedirectToAction("index", "home", new HomeViewModel() { LoginResult = res } );
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("index", "home", new HomeViewModel());
        }
    }
}
